package org.tony.spider.common;

import java.io.IOException;
import java.nio.charset.Charset;
import java.util.Iterator;
import java.util.Map;

import org.apache.http.HttpHost;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.conn.params.ConnRoutePNames;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.params.CoreProtocolPNames;
import org.apache.http.util.EntityUtils;

public class GetRequestor
{
  private HttpClient client;

  protected void initRequestor()
  {
    client = new DefaultHttpClient();
    {
      HttpHost proxy = new HttpHost("10.32.235.41", 8080);
      client.getParams().setParameter(ConnRoutePNames.DEFAULT_PROXY, proxy);
    }
    client.getParams().setParameter(CoreProtocolPNames.USER_AGENT, "Mozilla/5.0");
  }

  public void initialParams(Map<String, String> params)
  {
    for (Iterator<String> iter = params.keySet().iterator(); iter.hasNext();)
    {
      String pName = iter.next();
      client.getParams().setParameter(pName, params.get(pName));
    }
  }

  public String startGet(String requestUrl)
  {
    initRequestor();
    HttpGet get = new HttpGet(requestUrl);
    HttpResponse resp = null;
    String content = null;
    try
    {
      System.out.println("[start get url]:" + requestUrl);
      resp = client.execute(get);
      return EntityUtils.toString(resp.getEntity(), Charset.forName("GBK"));
    }
    catch (ClientProtocolException e)
    {
      System.out.println("ClientProtocolException ");
    }
    catch (IOException e)
    {
      System.out.println("IOException ");
    }
    finally
    {
      get.releaseConnection();
    }
    return content;
  }
}
